package com.lm.boot.service.impl;

import com.lm.boot.dao.UserMapper;
import com.lm.boot.dto.UserDto;
import com.lm.boot.entity.User;
import com.lm.boot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    public static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDto findUserById(Integer id) {
        String userKey = "user_" + id;
        ValueOperations<String,UserDto> operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(userKey)){
            UserDto userDto = operations.get(userKey);
            LOG.info("从缓存获取");
            return userDto;
        }

        User user = userMapper.getById(id);
        if (user != null){
            UserDto dto = new UserDto();
            BeanUtils.copyProperties(user, dto);

            operations.set(userKey,dto);
            LOG.info("从db查询并保存缓存");
            return  dto;
        }

        return null;
    }
}
